package com.example.big_orange2.authorization.manager.impl;

import com.example.big_orange2.authorization.manager.TokenManager;
import com.example.big_orange2.entity.Staff;
import com.example.big_orange2.entity.User;
import com.example.big_orange2.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTokenManager implements TokenManager {

    @Autowired
    private RedisUtils redisUtils;



    /**
     * 创建token
     * @param userInfo
     * @return
     */
    @Override
    public String getToken(User userInfo){
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        //String token_format=String.format(Constants.TOKEN_FORMAT,token);
        redisUtils.set(token,userInfo,2, TimeUnit.HOURS);
        return token;
    }

    @Override
    public String getToken(Staff staffInfo){
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        //String token_format=String.format(Constants.TOKEN_FORMAT,token);
        redisUtils.set(token,staffInfo,2, TimeUnit.HOURS);
        return token;
    }
    /**
     * 创建token
     * @param staffInfo
     * @return
     */
    @Override
    public String getTokenS (Staff staffInfo){
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        //String token_format=String.format(Constants.TOKEN_FORMAT,token);
        redisUtils.set(token,staffInfo,2, TimeUnit.HOURS);
        return token;
    }

    /**
     * 刷新用户
     * @param token
     */
    @Override
    public void refreshUserToken(String token){
        //token=String.format(Constants.TOKEN_FORMAT,token);
        if(redisUtils.hasKey(token)){
            redisUtils.expire(token, 2, TimeUnit.HOURS);
        }
    }

    /**
     * 用户退出登陆
     * @param token
     */
    @Override
    public void loginOff(String token){
        //  token=String.format(Constants.TOKEN_FORMAT,token);
        redisUtils.del(token);
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    @Override
    public User getUserInfoByToken(String token){
        // token=String.format(Constants.TOKEN_FORMAT,token);
        if(redisUtils.hasKey(token)){
            return (User) redisUtils.get(token);
        }
        return null;
    }

}
